import os
import re

def rename_files_by_reference(src_dir="1", ref_dir="2"):
    # 匹配文件名中的日期
    date_pattern = re.compile(r"(\d{8})")

    # 先构建参考映射：日期 -> 新文件名
    mapping = {}
    for filename in os.listdir(ref_dir):
        match = date_pattern.search(filename)
        if match:
            date = match.group(1)
            mapping[date] = filename
    if not mapping:
        print(f"⚠️ 在 {ref_dir} 中未找到带日期的文件。")
        return

    renamed = []
    skipped = []

    for filename in os.listdir(src_dir):
        match = date_pattern.search(filename)
        if not match:
            skipped.append(filename)
            continue

        date = match.group(1)
        if date not in mapping:
            skipped.append(filename)
            continue

        new_name = mapping[date]
        old_path = os.path.join(src_dir, filename)
        new_path = os.path.join(src_dir, new_name)

        # 避免覆盖已有文件
        if os.path.exists(new_path):
            print(f"⚠️ 目标文件已存在，跳过：{new_path}")
            continue

        os.rename(old_path, new_path)
        renamed.append((filename, new_name))

    # 输出结果
    if renamed:
        print("✅ 已成功重命名以下文件：")
        for old, new in renamed:
            print(f"  {old} → {new}")
    else:
        print("ℹ️ 没有文件被重命名。")

    if skipped:
        print("\n以下文件未匹配到对应日期，已跳过：")
        for f in skipped:
            print(f"  - {f}")

if __name__ == "__main__":
    rename_files_by_reference("1", "2")
